import VueRouter from "vue-router";
import Vue from "vue";
import routes from '@/router/routes'
import store from "@/store";

Vue.use(VueRouter)

//路由的push方法重复点击会报错，需要重写
//重写push方法
const oldPush = VueRouter.prototype.push
VueRouter.prototype.push = function (location, onComplete = () => {
}, onAbort = () => {
}) {
    return oldPush.call(this, location, onComplete, onAbort)
}
//重写replace方法
const oldReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function (location, onComplete = () => {
}, onAbort = () => {
}) {
    return oldReplace.call(this, location, onComplete, onAbort)
}

const router = new VueRouter({
    mode: 'history',
    routes,
    scrollBehavior: (to, from, savedPosition) => {
        return {x: 0, y: 0}
    }
})

//全局前置守卫(权限控制)
router.beforeEach(async (to, from, next) => {
    const token = store.state.user.token
    const whitePath = [
        'Login', 'Register', 'AddCartSuccess', 'Home', 'Search',
        'Detail', 'ShopCart'
    ]
    //判断是否有token
    if (token) {
        //如果有token
        //判断去向：
        // 1.如果去的是登录页(定向至首页)
        // 2.如果不是登录页
        //获取用户信息
        //1.获取到用户信息(放行)
        //2.获取不到用户信息(定向至登录页)
        console.log(1)
        if (to.name === 'Login' || to.name === 'Register') {
            console.log(2)
            next('/home')
        } else {
            const userInfo = !!store.state.user.userInfo.nickName;
            if (userInfo) {
                console.log(3)
                next()
            } else {
                console.log(4)
                try {
                    console.log('5')
                    await store.dispatch('user/getUserInfo')
                    next()
                } catch (e) {
                    console.log('6')
                    store.dispatch('user/resetUser')
                    next(`/login?redirect=${to.name}`)
                }
            }
        }
    } else {
        //如果没有token
        //是否在白名单内
        //1.在白名单内(放行)
        //2.不再白名单内(定向至登录页)
        if (whitePath.includes(to.name)) {
            console.log(7)
            next()
        } else {
            console.log(8)
            next(`/login?redirect=${to.name}`)
        }
    }
})

export default router